package com.xmtlxx.common.utils.ftp;

import com.jcraft.jsch.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * @author RonyChan
 * @since 2022/4/11 11:00
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SftpUtil {

//    @Value("${sftp.client.host}")
//    private String host;
//
//    //端口号
//    @Value("${sftp.client.port}")
//    private Integer port;
//
//    //用户名
//    @Value("${sftp.client.username}")
//    private String username;
//
//    //密码
//    @Value("${sftp.client.password}")
//    private String password;

//    //session链接超时时间
//    @Value("${sftp.client.sessionConnectTimeout}")
//    private Integer sessionConnectTimeout;
//
//    //channel链接超时时间
//    @Value("${sftp.client.channelConnectedTimeout}")
//    private Integer channelConnectedTimeout;

    private static Integer sessionConnectTimeout = 15000;
    private static Integer channelConnectedTimeout = 15000;


    /**
     * 检查SFTP目录或文件是否存在
     *
     * @param remotePath
     * @return
     */
    public boolean checkFileExist(String remotePath,String host,Integer port,String username,String password) {
        ChannelSftp channelSftp = loginSftp(host,port,username,password);
        try {
            channelSftp.ls(remotePath);
            return true;
        } catch (SftpException e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                return false;
            }
        }
        return false;
    }

    /**
     * 文件上传
     *
     * @param localFilePath
     * @param remoteDirPath
     * @return
     */
    public static boolean uploadFile(String localFilePath, String remoteDirPath, String host, Integer port, String username, String password) {
        ChannelSftp channelSftp = loginSftp(host,port,username,password);
        try {
            boolean dirs = createDirs(remoteDirPath, channelSftp);
            if (!dirs) {
                log.error("Remote path error. path:{}", remoteDirPath);
                return false;
            }
            String remoteFilePath = remoteDirPath + "/" + new File(localFilePath).getName();
            channelSftp.put(localFilePath, remoteFilePath);

            log.info("upload file success:::{}", remoteFilePath);

            return true;
        } catch (SftpException ex) {
            log.error("Error upload file", ex);
        } finally {
            logoutSftp(channelSftp);
        }
        return false;
    }


    /**
     * 文件下载
     *
     * @param localDirPath
     * @param remoteFilePath
     * @return
     */
    public static String downloadFile(String localDirPath, String remoteFilePath,String host,Integer port,String username,String password) {
        ChannelSftp channelSftp = loginSftp(host,port,username,password);
        OutputStream outputStream = null;
        try {
            String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);

            if (!new File(localDirPath).exists()) {
                new File(localDirPath).mkdirs();
            }

            String localFilePath = localDirPath + "/" + fileName;
            File file = new File(localFilePath);
            outputStream = new FileOutputStream(file);
            channelSftp.get(remoteFilePath, outputStream);

            file.createNewFile();
            return localFilePath;
        } catch (SftpException | IOException ex) {
            ex.printStackTrace();
        } finally {
            logoutSftp(channelSftp);
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 下载目录下的所有文件
     *
     * @param directory：要列出的目录
     * @return
     * @throws SftpException
     */
    public static Vector listFiles(String directory, String host,Integer port,String username,String password) throws SftpException {
        ChannelSftp channelSftp = loginSftp(host,port,username,password);
        return channelSftp.ls(directory);
    }

    /**
     * 下载目录下的所有文件
     *
     * @param directory：要列出的目录
     * @return
     * @throws SftpException
     */
    public static List<Map<String,String>> downRemoteFiles(String localDirPath,String directory, String host,Integer port,String username,String password){
        ChannelSftp channelSftp = loginSftp(host,port,username,password);
        OutputStream outputStream = null;
        try{
            List<Map<String,String>> result = new ArrayList<>();
            Vector vector = channelSftp.ls(directory);  //路径下所有文件
            if(vector.size() > 0){
                log.info("{}目录下文件数量::{}",directory,vector.size());
                Iterator it = vector.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                    String fileName = entry.getFilename();//路径下某个文件名称名称
                    String updateTime = entry.getAttrs().getMtimeString();
                    String downFile = directory+"/"+fileName;
                    if (!new File(localDirPath).exists()) {
                        new File(localDirPath).mkdirs();
                    }

                    String localFilePath = localDirPath + "/" + fileName;
                    File file = new File(localFilePath);
                    outputStream = new FileOutputStream(file);
                    channelSftp.get(downFile, outputStream);

                    file.createNewFile();
                    Map<String,String> item = new HashMap<>();
                    item.put("filePath",localFilePath);
                    item.put("updateTime",updateTime);
                    result.add(item);
                    log.info("文件{}已下载::{}",downFile,localFilePath);
                }
            }
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            logoutSftp(channelSftp);
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 登录SFTP
     *
     * @return
     */
    private static ChannelSftp loginSftp(String host, Integer port, String username, String password) {
        JSch jsch = new JSch();
        try {
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            sshSession.setConfig("StrictHostKeyChecking", "no");
            sshSession.connect(sessionConnectTimeout);
            Channel channel = sshSession.openChannel("sftp");
            channel.connect(channelConnectedTimeout);
            ChannelSftp channelSftp = (ChannelSftp) channel;
            log.info("登录成功");
            return channelSftp;
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭SFTP
     *
     * @param channelSftp
     */
    private static void logoutSftp(ChannelSftp channelSftp) {
        try {
            if (channelSftp == null) {
                return;
            }
            if (channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (channelSftp.getSession() != null) {
                channelSftp.getSession().disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 创建SFTP目录，如果目录不存在就创建
     *
     * @param dirPath
     * @param sftp
     * @return
     */
    private static boolean createDirs(String dirPath, ChannelSftp sftp) {
        if (StringUtils.isNotBlank(dirPath)) {
            String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::isNotBlank).toArray(String[]::new);
            for (String dir : dirs) {
                try {
                    sftp.cd(dir);
                    log.info("Change directory {}", dir);
                } catch (Exception e) {
                    try {
                        sftp.mkdir(dir);
                        log.info("Create directory {}", dir);
                    } catch (SftpException e1) {
                        log.error("Create directory failure, directory:{}", dir, e1);
                        e1.printStackTrace();
                        return false;
                    }
                    try {
                        sftp.cd(dir);
                        log.info("Change directory {}", dir);
                    } catch (SftpException e1) {
                        log.error("Change directory failure, directory:{}", dir, e1);
                        e1.printStackTrace();
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
//        loginSftp("b2b2test.inditex.com",22,"UB2BTRFIDRECALLPRE","A*ncW7XIjb");
        uploadFile("/Users/rony/data/json/push/getTagsRFID_1002_request.json", "/TO_ITX/TAGS_WITH_ORDER","127.0.0.1",1988,"ronychan","13599518139");
    }

}
